<!--  -->
<template>
   <div class='managepage'>
    <a-space>
    <span>类型:</span><a-select  style="width: 120px" @change="handleChange">
      <a-select-option v-for="(item,index) in alltype" :key="index" :value="item">
        {{ item }}
      </a-select-option>
    </a-select>
    <span>关键字:</span><a-input-search placeholder="输入关键字" v-model="serachtext" style="width: 200px" @search="onSearch" />
    <a-button type="primary" @click="addbook()">
          新增
    </a-button>
  </a-space>
  <p></p>
  <a-table
    bordered
    :columns="columns"
    :row-key="record => record.id"
    :data-source="tableData"
    :pagination="pagination"
    :loading="loading"
    @change="handleTableChange"
  >
    <template slot="img" slot-scope="img">
      <img class="tbimg" :src="img" />
    </template>
    <template slot="commend" slot-scope="commend,list">
      <a-switch v-if="commend == 1" default-checked @click="changeCommen(list.id)" />
      <a-switch v-else @click="changeCommen(list.id)"/>

    </template>
    <template slot="update_time" slot-scope="update_time">
      {{moment(update_time).format('YYYY/MM/DD')}}
    </template>
    <template slot="action" slot-scope="id,list">
      <a-space>
        <a-button type="primary" @click="updataItem(list)">
          修改
        </a-button>
        <a-button type="danger" @click="removeItem(id)">
          删除
        </a-button>
    </a-space>
    </template>
  </a-table>
    <a-modal
      :title="isadd ? '新增书籍' : '修改信息'"
      :visible="visible"
      :confirm-loading="confirmLoading"
      okText="确定"
      cancelText="取消"
      @ok="handleOk"
      @cancel="handleCancel"
      centered
    >
    <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules"  ref="ruleForm">
    <a-form-model-item label="书名" prop="title">
      <a-input v-model="form.title" />
    </a-form-model-item>
    <a-form-model-item label="作者" prop="authors">
      <a-input v-model="form.authors" />
    </a-form-model-item>
    <a-form-model-item label="类型" prop="type">
      <a-input v-model="form.type" />
    </a-form-model-item>
    <a-form-model-item label="图片">
      <a-upload
        name="avatar"
        list-type="picture-card"
        class="avatar-uploader"
        :show-upload-list="false"
        @change="handleChangeimg"
        :customRequest="customRequest"
      >
        <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
        <div v-else>
          <a-icon :type="loadingimg ? 'loading' : 'plus'" />
          <div class="ant-upload-text">
            上传
          </div>
    </div>
  </a-upload>
    <a-alert  message="建议上传长宽1:1.4" banner />
    </a-form-model-item>
    <a-form-model-item label="介绍" prop="arttext">
      <a-textarea v-model="form.arttext" :auto-size="{ minRows: 3, maxRows: 5 }" />
    </a-form-model-item>
  </a-form-model>
    </a-modal>
   </div>
</template>

<script>

// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { getWebAllBook, changeCommen, postbook, deletebook, putbook } from '@/api/webapi.js'
import { bookSearch } from '@/api/api.js'
function getBase64 (img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
const columns = [
  {
    title: '序号',
    customRender: (text, record, index) => `${index + 1}`,
    width: '70px'
  },
  {
    title: '书名',
    dataIndex: 'title',
    width: '200px'
  },
  {
    title: '作者',
    dataIndex: 'authors'
  },
  {
    title: '图片',
    dataIndex: 'img',
    scopedSlots: { customRender: 'img' }
  },
  {
    title: '类型',
    dataIndex: 'type'
  },
  {
    title: '推荐',
    dataIndex: 'commend',
    scopedSlots: { customRender: 'commend' }
  },
  {
    title: '操作',
    dataIndex: 'id',
    scopedSlots: { customRender: 'action' },
    width: '120px'
  }
  // {
  //   title: '更新日期',
  //   dataIndex: 'update_time',
  //   scopedSlots: { customRender: 'update_time' }
  // }
]
export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    // 这里存放数据
    return {
      isadd: true,
      confirmLoading: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      visible: false,
      tableData: [],
      pagination: {
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'], // 每页中显示的数据
        showTotal: total => `共有 ${total} 条数据` // 分页中显示总的数据
      },
      loading: false,
      columns,
      serachtext: '',
      alltype: ['全部', '世界名著', '中国当代', '外国现当代', '历史', '散文随笔'],
      booktype: '',
      form: {
        title: '',
        authors: '',
        type: '',
        arttext: ''
      },
      loadingimg: false,
      imageUrl: '',
      imageFile: null,
      rules: {
        title: [{ required: true, message: '书名不能为空', trigger: 'blur' }],
        authors: [{ required: true, message: '作者不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
        arttext: [{ required: true, message: '介绍不能为空', trigger: 'blur' }]
      },
      updataBookId: ''
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    changeCommen (id) {
      changeCommen(id).then((res) => {
        if (res.code === 200) {

        } else {
          this.$message.error('切换失败')
        }
      })
    },
    handleOk () {
      if (this.isadd === false) {
        if (this.updataBookId === '') {
          return this.$message.error('未知错误')
        }
        const formData = new FormData()
        // formData.append('img', this.imageFile.originFileObj)
        formData.append('title', this.form.title)
        formData.append('author_name', this.form.authors)
        formData.append('type', this.form.type)
        formData.append('arttext', this.form.arttext)
        putbook(this.updataBookId, formData).then((res) => {
          if (res.code === 200) {
            this.visible = false
            this.$refs.ruleForm.resetFields()
            this.imageFile = ''
            this.imageUrl = ''
            this.getBook({
              pageSize: this.pagination.pageSize,
              page: this.pagination.current
            })
          }
        })
        console.log('update模块')
      } else {
        if (this.imageFile === '') {
          return this.$message.error('请上传图片')
        }
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            const formData = new FormData()
            formData.append('img', this.imageFile.originFileObj)
            formData.append('title', this.form.title)
            formData.append('author_name', this.form.authors)
            formData.append('type', this.form.type)
            formData.append('arttext', this.form.arttext)
            postbook(formData).then((res) => {
              if (res.code === 200) {
                this.visible = false
                this.$refs.ruleForm.resetFields()
                this.imageFile = ''
                this.imageUrl = ''
                this.getBook()
              } else {
                this.$message.error('新增失败')
              }
            })
          } else {
            return false
          }
        })
      }
    },
    handleCancel () {
      this.$refs.ruleForm.resetFields()
      this.imageFile = ''
      this.imageUrl = ''
      this.visible = false
    },
    updataItem (list) {
      this.updataBookId = list.id
      this.form.title = list.title
      this.form.authors = list.authors[0]
      this.form.type = list.type
      this.form.arttext = list.arttext
      this.imageUrl = list.img
      this.isadd = false
      this.visible = true
    },
    updatebook (id, list) {
      console.log('fuckyoi')
      putbook(id, list).then((res) => {

      })
    },
    removeItem (id) {
      deletebook(id).then((res) => {
        if (res.code === 200) {
          this.getBook({
            pageSize: this.pagination.pageSize,
            page: this.pagination.current
          })
        }
      })
    },
    addbook () {
      this.isadd = true
      this.visible = true
    },
    handleTableChange (pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      pager.pageSize = pagination.pageSize
      this.pagination = pager
      if (this.booktype !== '' || this.serachtext !== '') {
        this.bookParams({
          pageSize: pagination.pageSize,
          page: pagination.current
        })
        return
      }
      this.getBook({
        pageSize: pagination.pageSize,
        page: pagination.current
      })
    },
    handleChange (value) {
      this.booktype = value
      if (value === '全部') {
        this.booktype = ''
      }
      this.bookParams()
    },
    bookParams (params) {
      const obj = {
        title: this.serachtext,
        type: this.booktype,
        ...params
      }
      this.loading = true
      bookSearch(obj).then((res) => {
        if (res.code === 200) {
          this.tableData = res.data.results
          const pagination = { ...this.pagination }
          pagination.total = res.data.count
          this.loading = false
          this.pagination = pagination
        } else {
          this.$message.error(res.msg)
          this.loading = false
        }
      })
    },
    onSearch () {
      if (this.serachtext === '') {
        this.getBook()
        return
      }
      this.bookParams()
    },
    getBook (params) {
      this.loading = true
      getWebAllBook(params).then((res) => {
        if (res.code === 200) {
          this.tableData = res.data.results
          const pagination = { ...this.pagination }
          pagination.total = res.data.count
          this.loading = false
          this.pagination = pagination
        }
      })
    },
    customRequest () {
    },
    handleChangeimg (uploadimg) {
      const file = uploadimg.file
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('只能上传图片格式')
      }
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!isLt2M) {
        this.$message.error('只能上传小于1MB的图片!')
      }
      if (isJpgOrPng && isLt2M) {
        // Get this url from response in real world.
        getBase64(file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
        })
        this.imageFile = file
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.getBook()
  }
}
</script>
<style lang='less' scoped>
.managepage{
}
.tbimg{
  width: 32px;
  height: 45px;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
  img{
    width: 100%;
  }
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.ant-upload.ant-upload-select-picture-card{
  width: 100px;
  height: 140px;
}
</style>
